import axios from 'axios'

const http = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
})

http.interceptors.request.use(config => {
  const token = sessionStorage.getItem('token')
  if (token) {
    config.headers.Authorization = token
  }
  else {
    config.headers.Authorization = ''
  }
  return config
})

http.interceptors.response.use(
  response => {
    if (response.status === 200) {
      const { code, data, msg } = response.data
      if (code === 0) {
        return data
      }
      else {
        message.error(msg)
        return Promise.reject(response.data)
      }
    }
    else {
      message.error(response.data.msg)
      return Promise.reject(response.data)
    }
  },
  error => {
    if (error.response.status === 401) {
      message.error('请先登录')
      sessionStorage.removeItem('token')
      window.location.href = '/login'
    }
    if (error.response.status === 403) {
      message.error('权限不足')
      sessionStorage.removeItem('token')
      window.location.href = '/login'
    }
    if (error.response.status === 500) {
      message.error('服务器错误')
    }
    return Promise.reject(error)
  },
)

export function httpRequest<T>(url: string, data: T): Promise<any> {
  return http.post(url, data)
}

export default httpRequest
